package com.tianji.order.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.common.Result;
import com.tianji.order.mapper.OrdersMapper;
import com.tianji.order.pojo.Orders;
import com.tianji.order.service.OrdersService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 陈佳
 * @since 2024-10-13
 */
@Service
@RequiredArgsConstructor
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    private final OrdersMapper ordersMapper;

    private final ExecutorService executorService = Executors.newFixedThreadPool(3);

    @Override
    public void createOrder(Long userId, BigDecimal amount) {
        Orders order = new Orders();
        order.setUserId(userId);
        order.setTotalAmount(amount);
        order.setStatus("未支付");
        ordersMapper.insert(order);
    }

    @Override
    public Result parkDataSummary() throws ExecutionException, InterruptedException {
        long startTime = System.currentTimeMillis();
        //异步执行三个任务
        Future<Map<String, Object>> contractInfo = executorService.submit(this::contractInfo);
        Future<Map<String, Object>> fleetInfo = executorService.submit(this::fleetInfo);
        Future<Map<String, Object>> tenantInfo = executorService.submit(this::tenantInfo);

        //获取结果，等待所有任务完成
        Map<String, Object> contractInfomap = contractInfo.get();
        Map<String, Object> fleetInfmap = fleetInfo.get();
        Map<String, Object> tenantInfmap = tenantInfo.get();

        //汇总结果
        HashMap<String, Object> result = new HashMap<>();
        result.put("contractInfo", contractInfomap);
        result.put("fleetInfo", fleetInfmap);
        result.put("tenantInfo", tenantInfmap);
        return Result.success(result);
    }

    // 模拟获取合同信息
    private Map<String, Object> contractInfo() {
        HashMap<String, Object> map = new HashMap<>();
        simulateDelay(500);  // 模拟 500ms 的延迟
        map.put("contractInfo",500);
        return map;
    }

    // 模拟获取车队信息
    private Map<String, Object> fleetInfo() {
        HashMap<String, Object> map = new HashMap<>();
        simulateDelay(300);  // 模拟 500ms 的延迟
        map.put("fleetInfo",300);
        return map;
    }

    // 模拟获取租户信息
    private Map<String, Object> tenantInfo() {
        HashMap<String, Object> map = new HashMap<>();
        simulateDelay(800);
        map.put("tenant",800);
        return map;
    }

    private void simulateDelay(long millis) {
        try {
            Thread.sleep(millis);
        }catch (InterruptedException e){
            Thread.currentThread().interrupt();
        }
    }
}
